/*
 * @lc app=leetcode.cn id=25 lang=java
 *
 * [25] K 个一组翻转链表
 */

// @lc code=start

import java.util.ArrayList;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    // public ListNode reverseKGroup(ListNode head, int k) {
    //     ListNode dummy = new ListNode();
    //     ListNode tmp;
    //     while (head != null) {
    //         tmp = head.next;
    //         head.next = dummy.next;
    //         dummy.next = head;
    //         head = tmp;
    //     }
    //     return dummy.next;
    // }

    /**
     * 62/62 cases passed (0 ms)
    Your runtime beats 100 % of java submissions
    Your memory usage beats 94.45 % of java submissions (41.7 MB)
     */
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode();
        ListNode pre = dummy;
        ListNode tmp;
        ListNode cur = head;
        ListNode[] list = new ListNode[k];
        int count = 0;
        while (cur != null) {
            tmp = cur.next;
            list[count++] = cur;
            if (count == k) {
                for (int i = k - 1; i >= 0; i--) {
                    pre.next = list[i];
                    pre = pre.next;
                }
                pre.next = tmp;
                count = 0;
            }
            cur = tmp;
        }

        return dummy.next;
    }
}
// @lc code=end
